const http = require('http')
const https = require('https')
//const fs = require('fs')
const unzipper = require('unzipper')
const querystring = require('querystring')

const client_id = 'Iv1.d1f4d22e7103febe'
const client_secret = '339bf351dfef3fb2d70220dedc8b7e9d889bb0f4'
//2. auth路由：接受code，用code+client_id+client_secret换token
function auth(request, response) {
    let query = querystring.parse(request.url.match(/^\/auth\?([\s\S]+)$/)[1])
    getToken(query.code, function(info) {
        console.log(info)
        //response.write(JSON.stringify(info))
        response.write(`<a href='http://localhost:8083/?token=${info.access_token}'>publish</a>`)
        response.end()
    })
}

function getToken(code, callback) {
    let request = https.request({
        hostname: 'github.com',
        path: `/login/oauth/access_token?code=${code}&client_id=${client_id}&client_secret=${client_secret}`,
        port: 443,
        method: 'POST'
    }, response => {
        let body = ''
        response.on('data', chunk => {
            body += chunk.toString()
        })
        response.on('end', () => {
            callback(querystring.parse(body))
        })
    })
    request.end()
}

//4. publish路由：用token获取用户信息，检查权限，接受发布
function publish(request, response) {
    let query = querystring.parse(request.url.match(/^\/publish\?([\s\S]+)$/)[1])
    getUser(query.token, info => {
        if (info.login === 'luyanfei') {
            reqest.pipe(unzipper.Extract({path: '../server/public/'}))
            request.on('end', function() {
                response.end('success')
            })
        }
    })
}

function getUser(token, callback) {
    let request = http.request({
            hostname: 'api.github.com',
            port: 443,
            method: 'GET',
            path: '/user',
            headers: {
                Authorization: `token ${token}`,
                'User-Agent': 'toy-publish'
            }
        }, response => {
            let body = ''
            response.on('data', chunk => {
                body += chunk.toString()
            })
            response.on('end', () => {
                callback(JSON.parse(body))
            })
        })
    request.end()
}

http.createServer(function(req, res) {
    if (req.url.match(/^\/auth\?/)) {
        return auth(req, res)
    }
    if (req.url.match(/^\/publish\?/)) {
        return publish(req, res)
    }
    //let outFile = fs.createWriteStream('../server/public/sample.zip')
    //req.pipe(outFile)

    //req.pipe(unzipper.Extract({path: '../server/public/'}))

    /*
     * 用pipe以后，不再用事件。
    req.on('data', chunk => {
        outFile.write(chunk)
    })
    req.on('end', () => {
        outFile.end()
        res.write('success')
    })
    */
}).listen(8082)
